<template xmlns:v-action="">
    <a-card :bordered="false">
        <div class="table-page-search-wrapper">
            <a-form layout="inline" ref="queryAdminForm" :form="queryAdminForm">
                <a-row :gutter="48">
                    <a-col :md="8" :sm="24">
                        <a-form-item label="用户名">
                            <a-input v-decorator="['username',{ rules: [{ required: false}] }]"/>
                        </a-form-item>
                    </a-col>
                    <template v-if="advanced">
                        <a-col :md="8" :sm="24">
                            <a-form-item label="手机">
                                <a-input v-decorator="['phone',{ rules: [{ required: false}] }]"/>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="邮箱">
                                <a-input v-decorator="['email',{ rules: [{ required: false}] }]"/>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="昵称">
                                <a-input v-decorator="['nickName',{ rules: [{ required: false}] }]"/>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="状态">
                                <a-select placeholder="请选择" v-decorator="['status',{ rules: [{ required: false}] }]">
                                    <a-select-option value="">请选择</a-select-option>
                                    <a-select-option value="0">关闭</a-select-option>
                                    <a-select-option value="1">启用</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="用户类型：">
                                <a-select placeholder="请选择" v-decorator="['userType',{ rules: [{ required: false}] }]">
                                    <a-select-option value="">请选择</a-select-option>
                                    <a-select-option value="0">后台账号</a-select-option>
                                    <a-select-option value="1">店铺账号</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item label="角色名称">
                                <a-input v-decorator="['roleName',{ rules: [{ required: false}] }]"/>
                            </a-form-item>
                        </a-col>
                    </template>
                    <a-col :md="!advanced && 8 || 24" :sm="24">
                    <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                        <a-button type="primary" @click="handleSearchAdmin">查询</a-button>
                        <a-button style="margin-left: 8px" @click="handleSearchResetAdmin">重置</a-button>
                        <a @click="toggleAdvanced" style="margin-left: 8px">
                            {{ advanced ? '收起' : '展开' }}
                            <a-icon :type="advanced ? 'up' : 'down'"/>
                        </a>
                    </span>
                    </a-col>
                </a-row>
            </a-form>
        </div>

        <div class="table-operator">
            <a-button type="primary" v-action:ums_admin_add icon="plus" @click="handleAddAdmin">新建</a-button>
            <a-dropdown v-if="selectedRowKeys.length > 0">
                <a-menu slot="overlay">
                    <a-menu-item key="1" v-action:ums_admin_delete @click="handleBatchDeleteAdmin"><a-icon type="delete" />删除</a-menu-item>
                    <!-- lock | unlock -->
                    <a-menu-item key="2"><a-icon type="lock" />扩展</a-menu-item>
                </a-menu>
                <a-button style="margin-left: 8px">
                    批量操作 <a-icon type="down" />
                </a-button>
            </a-dropdown>
        </div>

        <!-- 列表  -->
        <s-table
                ref="table"
                size="default"
                rowKey="adminId"
                :columns="columns"
                :data="loadData"
                :alert="{ show: true, clear: true }"
                :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        >
            <template v-for="(col, index) in columns" v-if="col.scopedSlots" :slot="col.dataIndex" slot-scope="text">
                <div :key="index">
                    <template>{{ text }}</template>
                </div>
            </template>
            <template slot="status" slot-scope="text">
                <div v-if="text==1">启用</div>
                <div v-if="text==0">关闭</div>
            </template>
            <template slot="image" slot-scope="url">
                <a-avatar size="large" :src="url" v-if="url" />
            </template>
            <span slot="action" slot-scope="text, record" >
                <a @click="handleEditAdmin(record)" v-if="record.username!='admin'">编辑</a>
                <label v-if="record.username=='admin'">编辑</label>
                <a-divider type="vertical" />
                <a-dropdown>
                    <a class="ant-dropdown-link">
                        更多 <a-icon type="down" />
                    </a>
                    <a-menu slot="overlay">
                        <a-menu-item>
                            <a href="javascript:" @click="handleDetailAdmin(record)" >详情</a>
                        </a-menu-item>
                        <a-menu-item v-if="record.username!='admin'">
                            <a href="javascript:" v-if="record.status==1" @click="handleDisableStatusAdmin(record)">关闭</a>
                            <a href="javascript:" v-if="record.status==0" @click="handleDisableStatusAdmin(record)">启用</a>
                        </a-menu-item>
                        <a-menu-item v-if="record.username!='admin'">
                            <a href="javascript:" @click="handleDeleteAdmin(record)">删除</a>
                        </a-menu-item>
                    </a-menu>
                </a-dropdown>
            </span>
        </s-table>
        <!--   新建表单 -->
        <a-modal
                title="新建"
                :width="800"
                v-model="addModelVisible"
                :confirmLoading="addConfirmLoading"
                @ok="handleSaveAdmin"
        >
            <a-form :form="addAdminForm">
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="用户名"
                                hasFeedback >
                            <a-input v-decorator="[ 'username',{ rules: [{ required: true, message: '用户名' }] }]"/>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="密码"
                                hasFeedback >
                            <a-input-password v-decorator="[ 'password',{ rules: [{ required: true, message: '密码' }] }]"/>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="手机"
                                hasFeedback >
                            <a-input v-decorator="[ 'phone',{ rules: [{ required: false, message: '手机' }] }]"/>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="邮箱"
                                hasFeedback >
                            <a-input v-decorator="[ 'email',{ rules: [{ required: false, message: '邮箱' }] }]"/>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="昵称"
                                hasFeedback >
                            <a-input v-decorator="[ 'nickName',{ rules: [{ required: false, message: '昵称' }] }]"/>
                        </a-form-item>
                        <a-form-item
                                :labelCol="labelCol"
                                :wrapperCol="wrapperCol"
                                label="备注信息"
                                hasFeedback >
                            <a-input v-decorator="[ 'note',{ rules: [{ required: false, message: '备注信息' }] }]"/>
                        </a-form-item>
                <a-divider />
            </a-form>
        </a-modal>
        <!--   编辑 -->
        <a-modal
                title="编辑"
                :width="800"
                v-model="editModelVisible"
                :confirmLoading="editConfirmLoading"
                @ok="handleUpdateAdmin"
        >
            <a-form :form="editAdminForm">
                <a-form-item
                        :labelCol="labelCol"
                        :wrapperCol="wrapperCol"
                        label="用户名"
                        >
                    <a-input v-decorator="[ 'username',{ rules: [{ required: true, message: '用户名' }] }]" disabled="disabled"/>
                </a-form-item>
                <a-form-item
                        :labelCol="labelCol"
                        :wrapperCol="wrapperCol"
                        label="角色名称"
                        >
                    <a-select
                        ref="roleSelect"
                        show-search
                        placeholder="Select a person"
                        option-filter-prop="children"
                        style="width: 200px"
                        :filter-option="roleSelectFilterOption"
                        @change="handleRoleChange"
                        v-decorator="[ 'roleId',{ rules: [{ required: true, message: '角色' }] }]"
                    >
                        <a-select-option v-for="item in roleData" :key="item.roleId" :value="item.roleId">
                            {{item.roleName}}
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-divider />
            </a-form>
        </a-modal>
    </a-card>
</template>

<script>
    import { STable } from '@/components'
    import api from '@/api'
    import { deleteAdmin, updateAdmin, addAdmin, batchDeleteAdmin } from '@/api/adminApi'
    import { getRoleList } from '@/api/roleApi'

    export default {
        name: 'AdminList',
        data () {
        return {
            description: '',
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 }
            },
            queryAdminForm: this.$form.createForm(this, { name: 'query_form' }),
            addModelVisible: false,
            addConfirmLoading: false,
            addAdminForm: this.$form.createForm(this, { name: 'add_form' }),
            editAdminForm: this.$form.createForm(this, { name: 'edit_form' }),
            editAdminRecord: {},
            editModelVisible: false,
            editConfirmLoading: false,
            // 高级搜索 展开/关闭
            advanced: false,
            // 查询参数
            queryParam: {
            },
            // 表头

            columns: [
                {
                    title: '用户名',
                    dataIndex: 'username',
                    // width: '100',
                    sorter: false,
                    // scopedSlots: { customRender: '' },
                    needTotal: false
                },
                {
                    title: '手机',
                    dataIndex: 'phone',
                    // width: '100',
                    sorter: false,
                    // scopedSlots: { customRender: '' },
                    needTotal: false
                },
                {
                    title: '邮箱',
                    dataIndex: 'email',
                    // width: '100',
                    sorter: false,
                    // scopedSlots: { customRender: '' },
                    needTotal: false
                },
                {
                    title: '昵称',
                    dataIndex: 'nickName',
                    // width: '100',
                    sorter: false,
                    // scopedSlots: { customRender: '' },
                    needTotal: false
                },
                {
                    title: '头像',
                    dataIndex: 'avatar',
                    // width: '100',
                    sorter: false,
                    scopedSlots: { customRender: 'image' },
                    needTotal: false
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    // width: '100',
                    sorter: false,
                    scopedSlots: { customRender: 'status' },
                    // scopedSlots: { customRender: '' },
                    needTotal: false
                },
                {
                    title: '角色名称',
                    dataIndex: 'roleName',
                    // width: '100',
                    sorter: false,
                    // scopedSlots: { customRender: '' },
                    needTotal: false
                },
                {
                    title: '最后登录时间',
                    dataIndex: 'loginTime',
                    // width: '100',
                    sorter: false,
                    // scopedSlots: { customRender: '' },
                    needTotal: false
                },
                {
                    table: '操作',
                    dataIndex: 'action',
                    width: '150',
                    scopedSlots: { customRender: 'action' }
                }
            ],
            // 加载数据方法 必须为 Promise 对象
            loadData: parameter => {
            return this.$http.get(api.adminUrl, {
                    params: Object.assign(parameter, this.queryParam)
                }).then(res => {
                    return res.data
                }, err => {
                    this.$notification['error']({
                        message: '提示',
                        description: err.msg || '加载数据失败',
                        duration: 8
                    })
                    return { pageNo: 0, totalCount: 0, data: [] }
                })
            },
            selectedRowKeys: [],
            selectedRows: [],
            roleData: []
        }
        },
        components: {
            STable
        },
        methods: {
            // 搜索查询
            handleSearchAdmin () {
                this.queryParam = this.queryAdminForm.getFieldsValue()
                this.loadData = parameter => {
                    return this.$http.get(api.adminUrl, {
                    params: Object.assign(parameter, this.queryParam)
                    }).then(res => {
                        return res.data
                    })
                }
                this.$refs.table.refresh()
            },
             // 搜索重置
            handleSearchResetAdmin () {
                this.queryAdminForm.resetFields()
            },
            handleChangeAdmin (value, key, column, record) {
                record[column.dataIndex] = value
            },
            handleEditAdmin (record) {
                // 加载角色数据
                this.handleLoadRoleData()
                this.editAdminRecord = Object.assign({}, record)
                this.editModelVisible = true
                this.$nextTick(() => {
                    let values = this.editAdminForm.getFieldsValue()
                    for(let key in values) {
                        values[key] = this.editAdminRecord[key];
                        this.editAdminForm.setFieldsValue(values)
                    }
                })
            },
            // 新增
            handleAddAdmin () {
                this.addAdminRecord = {}
                this.addModelVisible = true
                this.addAdminForm.resetFields();
            },
             // 批量删除
            handleBatchDeleteAdmin () {
                let ids = this.selectedRowKeys
                let params = this.selectedRowKeys
                const that = this
                this.$confirm({
                    title: '警告',
                    content: `真的要批量删除 ${ids.length} 个吗?`,
                    okText: '删除',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk () {
                        // 在这里调用删除接口
                        return new Promise((resolve, reject) => {
                            batchDeleteAdmin(params)
                            .then(res => {
                                that.$refs.table.clearSelected()
                                        that.$refs.table.refresh()
                                        that.$notification['success']({
                                            message: '提示',
                                            description: res.msg || '删除成功',
                                            duration: 8
                                        })
                                resolve()
                            }).catch((err) => {
                            reject(err)
                            that.$notification['error']({
                                message: '提示',
                                description: err.msg || '删除失败',
                                duration: 8
                            })
                        })
                    }).catch(() => console.log('Oops errors!'))
                    },
                    onCancel () {
                        console.log('Cancel')
                    }
                })
            },
            edit (row) {
                row.editable = true
                // row = Object.assign({}, row)
            },
            // eslint-disable-next-line
            handleDeleteAdmin (row) {
                const that = this
                this.$confirm({
                    title: '警告',
                    content: `真的要删除吗?`,
                    okText: '删除',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk () {
                        // 在这里调用删除接口
                        return new Promise((resolve, reject) => {
                            deleteAdmin(row.adminId)
                    .then(res => {
                            that.$refs.table.refresh()
                                    that.$notification['success']({
                                        message: '提示',
                                        description: res.msg || '删除成功',
                                        duration: 8
                                    })
                            resolve()
                        }).catch((err) => {
                            reject(err)
                            that.$notification['error']({
                                message: '提示',
                                description: err.msg || '删除失败',
                                duration: 8
                            })
                        })
                    }).catch(() => console.log('Oops errors!'))
                    },
                    onCancel () {
                        console.log('Cancel')
                    }
                })
            },
            handleDetailAdmin (row) {
                console.log('============ handleDetail')
            },
            handleLoadRoleData () {
                if(!this.roleData || this.roleData.length === 0) {
                    let param = { 'pageNo': 1, 'pageSize': 10000 }
                    getRoleList(param)
                    .then(res => {
                        this.roleData = res.data.data;
                    })
                }
            },
            roleSelectFilterOption(input, option) {
                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
            },
            handleRoleChange (value, option) {
            },
            handleDisableStatusAdmin (row) {
                const that = this
                let txt = row.status === 1 ? '关闭' : '启用'
                this.$confirm({
                    title: '警告',
                    content: `真的要${txt}吗?`,
                    okText: txt,
                    okType: 'danger',
                    cancelText: '取消',
                    onOk () {
                        // 在这里调用更新接口
                        return new Promise((resolve, reject) => {
                            let params = { 'adminId': row.adminId,
                                'status': row.status === 1 ? 0 : 1 }
                            updateAdmin(row.adminId, params)
                    .then(res => {
                            that.$refs.table.refresh()
                                    that.$notification['success']({
                                        message: '提示',
                                        description: res.msg || '操作成功',
                                        duration: 8
                                    })
                            resolve()
                        }).catch((err) => {
                            reject(err)
                            that.$notification['error']({
                                message: '提示',
                                description: err.msg || '操作失败',
                                duration: 8
                            })
                        })
                    }).catch(() => console.log('Oops errors!'))
                    },
                    onCancel () {
                        console.log('Cancel')
                    }
                })
            },
            // 保存
            handleSaveAdmin () {
                this.addAdminForm.validateFields((err, values) => {
                    if (err) {
                        return;
                    }
                    this.addRecord = values
                    this.addConfirmLoading = true;
                    // 新增操作
                    addAdmin(this.addRecord)
                    .then(res => {
                        this.$notification['success']({
                            message: '提示',
                            description: res.msg || '操作成功',
                            duration: 8
                        })
                        this.addAdminForm.resetFields();
                        this.addModelVisible = false;
                        this.addConfirmLoading = false;
                        this.$refs.table.refresh()
                    })
                    .catch((err) => {
                        this.addConfirmLoading = false;
                        this.$notification['error']({
                            message: '提示',
                            description: err.msg || '操作失败',
                            duration: 8
                        })
                    });
                });
            },
            // 更新
            handleUpdateAdmin () {
                this.editAdminForm.validateFields((err, values) => {
                    if (err) {
                        return;
                    }
                    this.roleData.forEach(element => {
                        if(element.roleId === values.roleId) {
                            values.roleName = element.roleName;
                        }
                    });
                    this.editConfirmLoading = true;
                    let updateAdminId = this.editAdminRecord.adminId
                    console.log('Received values of editAdminForm: ', updateAdminId, values);
                    // 更新操作
                    updateAdmin(updateAdminId, values)
                            .then(res => {
                                this.$notification['success']({
                                    message: '提示',
                                    description: res.msg || '操作成功',
                                    duration: 8
                                })
                                this.editAdminForm.resetFields();
                                this.editModelVisible = false;
                                this.editConfirmLoading = false;
                                this.$refs.table.refresh()
                            })
                    .catch((err) => {
                            this.editConfirmLoading = false;
                        this.$notification['error']({
                            message: '提示',
                            description: err.msg || '操作失败',
                            duration: 8
                        })
                    });
                });
            },
            onSelectChange (selectedRowKeys, selectedRows) {
                this.selectedRowKeys = selectedRowKeys
                this.selectedRows = selectedRows
            },
            toggleAdvanced () {
                this.advanced = !this.advanced
            }
        }
    }
</script>

<style lang="less" scoped>
    .search {
        margin-bottom: 54px;
    }

    .fold {
        width: calc(100% - 216px);
        display: inline-block
    }

    .operator {
        margin-bottom: 18px;
    }

    @media screen and (max-width: 900px) {
        .fold {
            width: 100%;
        }
    }
</style>
